<?php

/**
 * This file is part of Webman AI.
 *
 * @author    walkor<walkor@workerman.net>
 * @copyright walkor<walkor@workerman.net>
 * @link      http://www.workerman.net/
 */

namespace plugin\ai\app\service;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use plugin\ai\app\model\AiModel;
use plugin\ai\app\model\AiUser;
use support\exception\BusinessException;
use support\Log;
use Throwable;

class User
{
    /**
     * @param $userId
     * @param $modelType
     * @return bool
     * @throws BusinessException
     */
    public static function reduceBalance($userId, $modelType): bool
    {
        return static::changeBalance($userId, $modelType, -1);
    }

    /**
     * @param $userId
     * @param $modelType
     * @return bool
     * @throws BusinessException
     */
    public static function addBalance($userId, $modelType): bool
    {
        return static::changeBalance($userId, $modelType, 1);
    }

    /**
     * @param $userId
     * @param $modelType
     * @return int|mixed
     */
    public static function getBalance($userId, $modelType)
    {
        $user = AiUser::where('user_id', $userId)->first();
        $balance = $user->balance ?: [];
        return $balance[$modelType] ?? 0;
    }

    /**
     * @param $userId
     * @param $modelType
     * @param int $value
     * @return bool
     * @throws BusinessException
     */
    public static function changeBalance($userId, $modelType, int $value = -1): bool
    {
        $user = AiUser::where('user_id', $userId)->first();
        $balance = $user->balance ?: [];
        if (!is_array($balance)) {
            throw new BusinessException("用户 $userId balance字段错误");
        }
        if (!isset($balance[$modelType])) {
            foreach (Common::getModelItems() as $model) {
                if (!isset($balance[$model->type])) {
                    $balance[$model->type] = $model->settings['regFreeCount']['value'] ?? 0;
                }
            }
            $user->balance = json_encode($balance, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
            $user->save();
        }
        if (!isset($balance[$modelType])) {
            throw new BusinessException("模型 $modelType 没有对应的处理器");
        }

        if ($balance[$modelType] + $value >= 0) {
            $balance[$modelType] += $value;
            $user->balance = json_encode($balance, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
            $user->save();
            return true;
        } else {
            return false;
        }
    }

    /**
     * 是否是VIP(vip未过期)
     * @param $userId
     * @param bool $expired
     * @return bool
     */
    public static function isVip($userId, bool &$expired = false): bool
    {
        $expired = false;
        $aiUser = AiUser::where('user_id', $userId)->first();
        if (!$aiUser || !$aiUser->expired_at) {
            return false;
        }
        $expired = strtotime($aiUser->expired_at) < time();
        if ($expired && $aiUser->expired_updated_at !== $aiUser->expired_at) {
            $balance = $aiUser->balance ?: [];
            foreach ($balance as $key => $value) {
                $balance[$key] = 0;
            }
            $aiUser->expired_updated_at = $aiUser->expired_at;
            $aiUser->balance = json_encode($balance, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
            $aiUser->save();
        }
        return !$expired;
    }

    /**
     * @param $userId
     * @return void
     */
    public static function resetBalanceIfExpired($userId)
    {
        $aiUser = AiUser::where('user_id', $userId)->first();
        if (!$aiUser) {
            return;
        }
        if (!$aiUser->expired_at || strtotime($aiUser->expired_at) > time() || $aiUser->expired_updated_at === $aiUser->expired_at) {
            return;
        }
        $aiUser->expired_updated_at = $aiUser->expired_at;
        $balance = $aiUser->balance ?: [];
        foreach ($balance as $key => $value) {
            $balance[$key] = 0;
        }
        $aiUser->balance = json_encode($balance, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
        $aiUser->save();
    }

    /**
     * 新用户新增会员信息，赠送相关余额
     * @param $userId
     * @return Builder|Model|object|AiUser|null
     */
    public static function getOrCreateUser($userId)
    {
        if ($aiUser = AiUser::where('user_id', $userId)->first()) {
            return $aiUser;
        }
        $balance = [];
        foreach (AiModel::get() as $model) {
            $settings = $model->settings;
            $balance[$model->type] = $settings['regFreeCount']['value'] ?? 0;
        }
        try {
            $aiUser = new AiUser();
            $aiUser->user_id = $userId;
            $aiUser->balance = json_encode($balance, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
            $aiUser->save();
        } catch (Throwable $e) {
            Log::error((string)$e);
        }
        return $aiUser;
    }

}